package com.mryang.hds.service.impl;

import com.mryang.hds.configs.AppException;
import com.mryang.hds.entity.PunchRecord;
import com.mryang.hds.mapper.NeedMapper;
import com.mryang.hds.mapper.PunchRecordMapper;
import com.mryang.hds.mapper.UserMapper;
import com.mryang.hds.entity.User;
import com.mryang.hds.service.IUserService;
import com.mryang.hds.utils.DateUtil;
import com.mryang.hds.utils.ResultCode;
import com.mryang.hds.utils.ResultJson;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Genius
 * @version 1.0.0
 * @ClassName UserServiceImpl.java
 * @Description TODO
 * @createTime 2022年12月24日 14:08:00
 */

@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    UserMapper userMapper;

    @Resource
    NeedMapper needMapper;

    @Resource
    PunchRecordMapper punchRecordMapper;

    @Override
    public List<User> getAllUser() {

        // 此处可能出现问题，需要try、catch
        List<User> user = null;

        try {
            user = userMapper.getAllUser();
            return user;
        }catch (Exception e){
            throw new AppException(ResultCode.USER_CREDIT_NOT_ENOUTH);
        }

    }

    @Override
    public User getUserById(Integer uid) {

        try {
            return userMapper.getUserById(uid);

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.USER_CREDIT_NOT_ENOUTH);
        }

    }

    @Override
    public int updatePwd(Integer uid, String newPwd) {
        try {
            // 修改用户密码
            return userMapper.updatePwd(uid, newPwd);

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.ERROR);
        }
    }

    @Override
    public void addUser(User user) {
        try {
            // 通过待添加用户的身份证号或手机号，去数据库比对，若数据库中已经包含该用户，则返回添加失败
            User userByIdCard = userMapper.getUserByIdCard(user.getIdCard());

            if (userByIdCard != null){
                throw new AppException(ResultCode.USERADD_FAIL);
            }else {
                // 添加新用户
                userMapper.addUser(user);
            }

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.USERADD_FAIL);
        }
    }

    @Override
    public ResultJson editUser(User user, User userOld){
        try {
            int count = 0;
            if (user.getUName().equals(userOld.getUName())){
                user.setUName(null);
                count++;
            }
            if (user.getGender().equals(userOld.getGender())){
                user.setGender(null);
                count++;

            }
            if (user.getStatus().equals(userOld.getStatus())){
                user.setStatus(null);
                count++;

            }
            if (user.getAge().equals(userOld.getAge())){
                user.setAge(null);
                count++;

            }
            if (user.getIdCard().equals(userOld.getIdCard())){
                user.setIdCard(null);
                count++;

            }
            if (user.getAddress().equals(userOld.getAddress())){
                user.setAddress(null);
                count++;

            }
            if (user.getPhone().equals(userOld.getPhone())){
                user.setPhone(null);
                count++;

            }
            if (user.getTripOk().equals(userOld.getTripOk())){
                user.setTripOk(null);
                count++;

            }
            if (user.getPunchInfo().equals(userOld.getPunchInfo())){
                user.setPunchInfo(null);
                count++;
            }
            if (count>=9){
                return ResultJson.error("您暂未进行任何修改！");
            }else{
                // System.out.println(user);

                userMapper.editUser(user.getUName(),
                        user.getAddress(),
                        user.getIdCard(),
                        user.getPhone(),
                        user.getUserId(),
                        user.getGender(),
                        user.getAge(),
                        user.getStatus(),
                        user.getTripOk(),
                        user.getPunchInfo());

                return ResultJson.success("信息修改成功");

            }


        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.ERROR);
        }
    }

    @Override
    public List<User> getUByCreator(String createId) {
        try {
            return userMapper.getUByCreator(createId);

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.ERROR);
        }
    }

    @Transactional
    @Override
    public Map<String, Integer> aboutMe(Integer userId) {
        try {
            Map<String,Integer> result = new HashMap<>();
            // 1、获取该用户的需求总量
            result.put("needNums",needMapper.getNeedCountById(userId,null));
            // 2、获取该用户的已完成需求数
            result.put("needIsOkNums",needMapper.getNeedCountById(userId,2));

            // 获取用户的创建时间
            String updateTime = userMapper.getUserById(userId).getUpdateTime();

            // 3、获取该用户的健康/危险/未打卡总数
            result.put("PRHealthNums",punchRecordMapper.getPRCountByDataException(userId,"正常",updateTime));
            result.put("PRBadNums",punchRecordMapper.getPRCountByDataException(userId,"异常",updateTime));
            result.put("PRNoPunchNums", punchRecordMapper.getPRCountByDataException(userId, "未打卡",updateTime));
            // 4、获取已隔离天数
            String[] split = updateTime.split("-");
            LocalDate givenDate = LocalDate.of(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
                // 计算指定日期到今天的天数
            long daysBetween = ChronoUnit.DAYS.between(givenDate, LocalDate.now());

            result.put("PRGeLiDays", (int) daysBetween);
            // 5、获取14天内的健康情况
                // 获取14天前的日期
            LocalDate today = LocalDate.now();
            String date14DaysAgo = today.minusDays(14).toString();
                // 获取指定日期到今天的健康数据情况
            result.put("PRHealthGeLiDays", punchRecordMapper.getPRCountByDataException(userId, "正常", date14DaysAgo));


            return result;

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.ERROR);
        }
    }

    @Override
    public List<PunchRecord> getPunchRecordById(Integer uid) {
        try {
            // 获取用户的创建时间
            String updateTime = userMapper.getUserById(uid).getUpdateTime();
            // 查询用户开始隔离至今的打卡情况
            List<PunchRecord> prCountByDataExceptionDatas = punchRecordMapper.getPRCountByDataExceptionDatas(uid, null, updateTime);

            return prCountByDataExceptionDatas;

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.ERROR);
        }

    }

    @Override
    public List<User> getAssmUser(Integer createOk) {
        try {
            return userMapper.getAssmUser(createOk);

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.ERROR);
        }

    }

    @Transactional
    @Override
    public void editSelectsUser(List<Integer> selectsId, String createId) {
        try {

            String time = DateUtil.dateToString(new Date(), "yyyy-MM-dd");

            for (Integer userId : selectsId) {

                userMapper.editSelectsUser(userId,createId,time);
            }

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.ERROR);
        }

    }

    @Override
    public List<User> searchNoAssm(String name, Integer createOk, String address) {
        try {

            return userMapper.searchNoAssm(name,createOk,address);

        }catch (Exception e){
            e.printStackTrace();
            throw new AppException(ResultCode.ERROR);
        }
    }

}
